package com.yry.ams.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.yry.ams.constant.BaiDuConstants;
import com.yry.ams.constant.CommonConstants;
import com.yry.ams.ex.BaseErrorException;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2021/11/4.
 */
@Data
public class BaiDuUtil {
    /**
     * 应用的API Key
     */
    private String clientId;
    /**
     * 应用的Secret Key
     */
    private String clientSecret;

    public BaiDuUtil(String clientId,String clientSecret){
        this.clientId =clientId;
        this.clientSecret =clientSecret;
    }

    private Map<String,Object> varMap = new HashMap<String,Object>();

    public String getAccessToken(){
        String accessToken = (String) varMap.get("baidu_oauth2_token");
        if(StringUtils.isEmpty(accessToken)){
            requestAccessToken();
            return (String) varMap.get("baidu_oauth2_token");
        }
        Date validDay = (Date)varMap.get("baidu_oauth2_token_validDay");
        Date curDate = new Date();
        if(curDate.getTime() >= validDay.getTime()){
            requestAccessToken();
            return (String) varMap.get("baidu_oauth2_token");
        }
        return accessToken;
    }

    public void putAccessToken(String accessToken,Integer expiresIn){
        varMap.put("baidu_oauth2_token",accessToken);
        Date validDay =(expiresIn==null||expiresIn<1)?new Date(): DateUtils.addSeconds(new Date(),expiresIn);
        varMap.put("baidu_oauth2_token_validDay",validDay);
    }

    private void requestAccessToken(){
        StringBuffer url = new StringBuffer();
        url.append(BaiDuConstants.REQ_ACCESS_TOKEN_URL)
                .append(CommonConstants.CON_1).append("grant_type=").append("client_credentials")
                .append(CommonConstants.CON_4).append("client_id=").append(clientId)
                .append(CommonConstants.CON_4).append("client_secret=").append(clientSecret);
        String reqResult= HttpUtil.post(url.toString(),"");
        JSONObject reqJson =JSONObject.parseObject(reqResult);
        String error =reqJson.getString("error");
        if(StringUtils.isNotEmpty(error)){
            throw new BaseErrorException("请求百度AccessToken出错： "+reqJson.getString("error_description"));
        }
        String accessToken = reqJson.getString("access_token");
        Integer expiresIn = reqJson.getInteger("expires_in"); // 有效时间，单位秒，有效期30天
        // 本地缓存
        putAccessToken(accessToken,(expiresIn-180) );
    }


    /**
     * 图片 通用物体和场景识别
     */
    public String imgGeneralDiscern(String imgUrl) throws IOException {

        StringBuffer url = new StringBuffer();
        url.append(BaiDuConstants.GENERAL_DISCERN_URL)
                .append(CommonConstants.CON_1).append("access_token=").append(getAccessToken());
        JSONObject param = new JSONObject();

        File imgLocalFile = new File(imgUrl);
        if(imgLocalFile.exists()){
            FileInputStream inputFile = new FileInputStream(imgLocalFile);
            byte[] buffer = new byte[(int)imgLocalFile.length()];
            inputFile.read(buffer);
            inputFile.close();
            param.put("image",new BASE64Encoder().encode(buffer));
        }else{
            param.put("url",imgUrl);
        }
        String reqResult= HttpUtil.post(url.toString(),param);
        return reqResult;
    }

}
